<!--
 * @Author: Olivia
 * @Date: 2022-12-06 23:20:12
 * @custom_string_Olivia: Less is more
-->
<template>
    <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
        :immediate-check="false"
        :error="error"
        error-text="请求失败，点击重新加载"
    >
  <comment-item
    v-for="(item, index) in list"
    :key="index"
    :comment="item"
    @reply-click="$emit('reply-click', $event)"
    />
</van-list>
</template>
<script>
import { getComments } from '@/api/comment'
import CommentItem from '../components/comment-item.vue'
export default {
  name: 'CommentList',
  data () {
    return {
    //   list: [],
      loading: false,
      finished: false,
      offset: null,
      limit: 0,
      error: false
    }
  },
  components: {
    CommentItem
  },
  props: {
    source: {
      type: [Number, String, Object],
      required: true
    },
    list: {
      type: Array,
      default: () => []
    },
    type: {
      type: String,
      validator (val) {
        return ['a', 'c'].includes(val)
      },
      default: 'a'
    }
  },
  created () {
    this.loading = true
    this.onLoad()
  },
  computed: {
  },
  methods: {
    async onLoad () {
      try {
        const { data } = await getComments({
          type: this.type, // 评论类型，a-对文章(article)的评论，c-对评论(comment)的回复
          source: this.source.toString(), // 源id，文章id或评论id
          offset: this.offset, // 获取评论数据的偏移量，值为评论id，表示从此id的数据向后取，不传表示从第一页开始读取数据
          limit: this.limit // 获取的评论数据个数，不传表示采用后端服务设定的默认每页数据量
        })
        const { results } = data.data
        this.$emit('onload-success', data.data)
        this.list.push(...results)
        // console.log(data.data)
        this.loading = false
        if (results.length) {
          this.offset = data.data.last_id
        } else {
          this.finished = true
        }
      } catch (error) {
        this.error = true
      }
    }
  }
}
</script>
<style lang='less'  scoped>

</style>
